package com.mai4j.maiadmin.misc;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
public class Utils {

    public static String toSnakeCase(String str) {
        if (str == null || "".equals(str.trim())) {
            return null;
        }
        if (str.length() == 1) {
            return str.toLowerCase();
        }
        StringBuilder buffer = new StringBuilder();
        boolean skip = false;
        char[] chars = str.toCharArray();
        for (int ch = 0; ch < chars.length; ch++) {
            char character = chars[ch];
            if (ch == 0) {
                buffer.append(Character.toLowerCase(character));
                continue;
            }
            if ('_' == character || '-' == character || ' ' == character) {
                buffer.append('_');
                skip = true;
                continue;
            }
            if (Character.isLowerCase(character) || Character.isDigit(character)) {
                buffer.append(character);
                continue;
            }
            char previous = chars[(ch - 1)];
            if (!Character.isLetter(previous) || Character.isLowerCase(previous)) {
                if (skip) {
                    skip = false;
                } else {
                    buffer.append('_');
                }
                buffer.append(Character.toLowerCase(character));
                continue;
            }
            if (ch < (chars.length - 1)) {
                char last = chars[(ch + 1)];
                if (Character.isLowerCase(last)) {
                    if (skip) {
                        skip = false;
                    } else {
                        buffer.append('_');
                    }
                    buffer.append(Character.toLowerCase(character));
                    continue;
                }
            }
            buffer.append(Character.toLowerCase(character));
        }
        return buffer.toString();
    }
}
